import React from "react";
import { Tabs, Space, Input, DatePicker, Form, Button, Modal, InputNumber } from "antd";
import TheButton from "@/components/TheButton";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import "@/views/commodity/style/style.less";
import { apiGetReturnOrderDetails, apiOrderRefundSubmitY, apiOrderRefundRefuse } from '@/request/orderManagement'
import { getDateTime3 } from '@/utils/getDate'
import TheDialog from '@/components/TheDialog'
import { exportSheetTable } from '@/utils/exportTable.js';

const { RangePicker } = DatePicker;
const { Search } = Input;
const { TabPane } = Tabs;
const { TextArea } = Input;

class Chargeback extends React.Component {
  roleIds = sessionStorage.getItem('roleName')
  FormRef = React.createRef()
  state = {
    salesReturnStatus: '',
    frozenVisible: false,
    orderId: "",
    columns1: [
      {
        title: "退单编号",
        dataIndex: "returnCode",
        key: "returnCode",
      },
      {
        title: "订单编号",
        dataIndex: "orderCode",
        key: "orderCode",
      },
      {
        title: "用户昵称",
        dataIndex: "orderMemberName",
        key: "orderMemberName",
      },
      {
        title: "订单金额（元）",
        dataIndex: "orderTotalPrice",
        key: "orderTotalPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderTotalPrice} />
        }
      },
      {
        title: "实付金额（元）",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "退款金额",
        dataIndex: "realRefundAmount",
        key: "realRefundAmount",
        render: (text, render) => {
          return <React.$Price price={render.realRefundAmount} />
        }
      },
      {
        title: "退单时间",
        dataIndex: "salesGoTime",
        key: "salesGoTime",
      },
      {
        title: "退单状态",
        dataIndex: "salesReturnStatus",
        key: "salesReturnStatus",
        render: (text, record) => {
          let label = ''
          switch (record.salesReturnStatus) {
            case 1:
              label = "退款中"
              break
            case 0:
              label = "退款失败"
              break
            case 9:
              label = "退款成功"
              break
            default:
              label = "未知退款状态"
          }
          return label;
        }
      },
      {
        title: "退单原因",
        dataIndex: "remark",
        key: "remark",
      },
      {
        title: "操作",
        fixed: "right",
        render: (text, render) => {
          return (
            <div>
              <TheButton
                hasPermi={['order:chargeback:view']}
                onClick={() => this.props.history.push(`/order/chargeback/details/${render.returnCode}`)}
              >
                查看订单
              </TheButton>

              {
                this.roleIds.includes('库管') ? null : <span>
                  <TheButton hasPermi={['order:chargeback:refund']} onClick={() => this.chargebackConfirm(render.returnCode, render.orderType, render.realRefundAmount)}>同意退款</TheButton>
                  <TheButton hasPermi={['order:chargeback:refund']} onClick={() => this.chargebackRefused(render.returnCode)}>拒绝退款</TheButton>
                </span>
              }

            </div>
          );
        },
      },
    ],
    columns: [
      {
        title: "退单编号",
        dataIndex: "returnCode",
        key: "returnCode",
      },
      {
        title: "订单编号",
        dataIndex: "orderCode",
        key: "orderCode",
      },
      {
        title: "用户昵称",
        dataIndex: "orderMemberName",
        key: "orderMemberName",
      },
      {
        title: "订单金额（元）",
        dataIndex: "orderTotalPrice",
        key: "orderTotalPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderTotalPrice} />
        }
      },
      {
        title: "实付金额（元）",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "退款金额",
        dataIndex: "realRefundAmount",
        key: "realRefundAmount",
        render: (text, render) => {
          return <React.$Price price={render.realRefundAmount} />
        }
      },
      {
        title: "退单时间",
        dataIndex: "salesGoTime",
        key: "salesGoTime",
      },
      {
        title: "退单状态",
        dataIndex: "salesReturnStatus",
        key: "salesReturnStatus",
        render: (text, record) => {
          let label = ''
          switch (record.salesReturnStatus) {
            case 1:
              label = "退款中"
              break
            case 0:
              label = "退款失败"
              break
            case 9:
              label = "退款成功"
              break
            default:
              label = "未知退款状态"
          }
          return label;
        }
      },
      {
        title: "退单原因",
        dataIndex: "remark",
        key: "remark",
      },
      {
        title: "操作",
        fixed: "right",
        render: (text, render) => {


          if (render.salesReturnStatus == 1) {
            return (
              <div>
                <TheButton
                  hasPermi={['order:chargeback:view']}
                  onClick={() => this.props.history.push(`/order/chargeback/details/${render.returnCode}`)}
                >
                  查看订单
                </TheButton>
                {
                  this.roleIds.includes('库管') ? null : <span>
                    <TheButton hasPermi={['order:chargeback:refund']} onClick={() => this.chargebackConfirm(render.returnCode, render.orderType, render.orderPayPrice)}>同意退款</TheButton>
                    <TheButton hasPermi={['order:chargeback:refund']} onClick={() => this.chargebackRefused(render.returnCode)}>拒绝退款</TheButton>
                  </span>
                }
              </div>
            );
          } else {
            return (
              <div>
                <TheButton
                  onClick={() => this.props.history.push(`/order/chargeback/details/${render.returnCode}`)}
                >
                  查看订单
                </TheButton>
              </div>
            )
          }

        },
      },
    ],
    columns0: [
      {
        title: "退单编号",
        dataIndex: "returnCode",
        key: "returnCode",
      },
      {
        title: "订单编号",
        dataIndex: "orderCode",
        key: "orderCode",
      },
      {
        title: "用户昵称",
        dataIndex: "orderMemberName",
        key: "orderMemberName",
      },
      {
        title: "订单金额（元）",
        dataIndex: "orderTotalPrice",
        key: "orderTotalPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderTotalPrice} />
        }
      },
      {
        title: "实付金额（元）",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "退款金额",
        dataIndex: "realRefundAmount",
        key: "realRefundAmount",
        render: (text, render) => {
          return <React.$Price price={render.realRefundAmount} />
        }
      },
      {
        title: "退单时间",
        dataIndex: "salesGoTime",
        key: "salesGoTime",
      },
      {
        title: "退单状态",
        dataIndex: "salesReturnStatus",
        key: "salesReturnStatus",
        render: (text, record) => {
          let label = ''
          switch (record.salesReturnStatus) {
            case 1:
              label = "退款中"
              break
            case 0:
              label = "退款失败"
              break
            case 9:
              label = "退款成功"
              break
            default:
              label = "未知退款状态"
          }
          return label;
        }
      },
      {
        title: "退单原因",
        dataIndex: "remark",
        key: "remark",
      },
      {
        title: "操作",
        fixed: "right",
        render: (text, render) => {
          return (
            <div>
              <TheButton
                onClick={() => this.props.history.push(`/order/chargeback/details/${render.returnCode}`)}
              >
                查看订单
              </TheButton>
            </div>
          );
        },
      },
    ],
    columns9: [
      {
        title: "退单编号",
        dataIndex: "returnCode",
        key: "returnCode",
      },
      {
        title: "订单编号",
        dataIndex: "orderCode",
        key: "orderCode",
      },
      {
        title: "用户昵称",
        dataIndex: "orderMemberName",
        key: "orderMemberName",
      },
      {
        title: "订单金额（元）",
        dataIndex: "orderTotalPrice",
        key: "orderTotalPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderTotalPrice} />
        }
      },
      {
        title: "实付金额（元）",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "退款金额",
        dataIndex: "realRefundAmount",
        key: "realRefundAmount",
        render: (text, render) => {
          return <React.$Price price={render.realRefundAmount} />
        }
      },
      {
        title: "退单时间",
        dataIndex: "salesGoTime",
        key: "salesGoTime",
      },
      {
        title: "退单状态",
        dataIndex: "salesReturnStatus",
        key: "salesReturnStatus",
        render: (text, record) => {
          let label = ''
          switch (record.salesReturnStatus) {
            case 1:
              label = "退款中"
              break
            case 0:
              label = "退款失败"
              break
            case 9:
              label = "退款成功"
              break
            default:
              label = "未知退款状态"
          }
          return label;
        }
      },
      {
        title: "退单原因",
        dataIndex: "remark",
        key: "remark",
      },
      {
        title: "操作",
        fixed: "right",
        render: (text, render) => {
          return (
            <div>
              <TheButton
                onClick={() => this.props.history.push(`/order/chargeback/details/${render.returnCode}`)}
              >
                查看订单
              </TheButton>
            </div>
          );
        },
      },
    ],
    dataSource: [],
    dataSource1: [],
    dataSource0: [],
    dataSource9: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    pageData1: {
      pageNo: 1,
      pageSize: 10,
    },
    pageData0: {
      pageNo: 1,
      pageSize: 10,
    },
    pageData9: {
      pageNo: 1,
      pageSize: 10,
    },
    total1: 0,
    total0: 0,
    total9: 0,
    tabData: [
      {
        label: '全部',
        value: ''
      },
      {
        label: '退款中',
        value: '1'
      },
      {
        label: '退款成功',
        value: '9'
      },
      {
        label: '退款失败',
        value: '0'
      },
    ],
    searchValue: {
      orderMemberName: '',
      orderTypeName: '',
      orderCode: '',
      returnCode: '',
      createTimeStart: '',
      createTimeEnd: ''
    },
    loading: false,
    orderId: '',
    visible: false
  };
  async componentDidMount() {
    await this.getData()
  }
  getData = async () => {
    this.setState({ loading: true })
    const { salesReturnStatus, searchValue } = this.state
    let res = await apiGetReturnOrderDetails({
      salesReturnStatus,
      ...searchValue,
      ...this.state[`pageData${salesReturnStatus}`]
    })
    if (res.data && res.code === 0) {
      this.setState({
        [`pageData${salesReturnStatus}`]: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        [`dataSource${salesReturnStatus}`]: res.data,
        [`total${salesReturnStatus}`]: res.totalCount,
        loading: false
      })
    } else {
      this.setState({ loading: false })
    }
  }
  setTabKey = (salesReturnStatus) => {
    this.setState({ salesReturnStatus }, () => {
      this.getData()
    })
  };
  pageChange = (pageNo, pageSize, index) => {
    this.setState({
      [`pageData${index}`]: {
        pageNo,
        pageSize,
      },
    }, () => this.getData());
  };
  dialogCancel = () => {
    this.setState({ visible: false });
  };
  chargebackConfirm = (orderId, type, orderPayPrice) => {
    if (type == 1) {
      this.setState({
        orderId,
        frozenVisible: true,
        orderPayPrice: React.$transNum(orderPayPrice, 2, -2)
      }, () => {
        this.FormRef.current.setFieldValue('changePrice', React.$transNum(orderPayPrice, 2, -2))
      })
    } else if (type == 2 || type == null) {
      React.$confirm({
        title: "您确认同意此订单退款吗？",
        onOk: async () => {
          let res = await apiOrderRefundSubmitY({ returnCode: orderId })
          if (res.code === 0) {
            React.$message({
              type: 'info',
              content: '退款成功'
            })
            this.getData()
          }
        },
      });
    }
  };
  modalConfirm = async () => {
    let res = await apiOrderRefundSubmitY({ returnCode: this.state.orderId, refundAmount: React.$transNum(this.state.orderPayPrice, 2, 2) })
    if (res.code === 0) {
      React.$message({
        type: 'info',
        content: '退款成功'
      })
      this.setState({
        frozenVisible: false,
      })
      this.getData()
    }
  }
  chargebackRefused = (orderId) => {
    this.setState({ visible: true, orderId })
  };
  onFinish = async value => {
    this.setState({ btnLoading: true })
    let res = await apiOrderRefundRefuse({ ...value, returnCode: this.state.orderId })
    if (res.code === 0) {
      React.$message({
        type: 'info',
        content: '拒绝退款成功'
      })
      this.handleCancel()
      this.getData()
    }
    this.setState({ btnLoading: false })
  }
  handleCancel = () => {
    this.setState({
      visible: false,
      orderId: ''
    })
  }
  setNickName = e => {
    this.setState({
      searchValue: {
        ...this.state.searchValue,
        memberName: e
      },
      pageData1: {
        pageNo: 1,
        pageSize: 10
      },
      pageData0: {
        pageNo: 1,
        pageSize: 10
      },
      pageData9: {
        pageNo: 1,
        pageSize: 10
      },
    }, () => {
      this.getData()
    })
  }
  setStoreName = e => {
    this.setState({
      searchValue: {
        ...this.state.searchValue,
        memberName: e
      },
      pageData1: {
        pageNo: 1,
        pageSize: 10
      },
      pageData0: {
        pageNo: 1,
        pageSize: 10
      },
      pageData9: {
        pageNo: 1,
        pageSize: 10
      },
    }, () => {
      this.getData()
    })
  }
  setOrderCode = e => {
    this.setState({
      searchValue: {
        ...this.state.searchValue,
        orderCode: e
      },
      pageData1: {
        pageNo: 1,
        pageSize: 10
      },
      pageData0: {
        pageNo: 1,
        pageSize: 10
      },
      pageData9: {
        pageNo: 1,
        pageSize: 10
      },
    }, () => {
      this.getData()
    })
  }
  setReturnCode = e => {
    this.setState({
      searchValue: {
        ...this.state.searchValue,
        returnCode: e
      },
      pageData1: {
        pageNo: 1,
        pageSize: 10
      },
      pageData0: {
        pageNo: 1,
        pageSize: 10
      },
      pageData9: {
        pageNo: 1,
        pageSize: 10
      },
    }, () => {
      this.getData()
    })
  }
  datePickerChange = e => {
    if (e) {
      this.setState({
        searchValue: {
          ...this.state.searchValue,
          createTimeStart: getDateTime3(e[0]),
          createTimeEnd: getDateTime3(e[1])
        },
        pageData1: {
          pageNo: 1,
          pageSize: 10
        },
        pageData0: {
          pageNo: 1,
          pageSize: 10
        },
        pageData9: {
          pageNo: 1,
          pageSize: 10
        },
      }, () => {
        this.getData()
      })
    } else {
      this.setState({
        searchValue: {
          ...this.state.searchValue,
          createTimeStart: '',
          createTimeEnd: ''
        },
        pageData1: {
          pageNo: 1,
          pageSize: 10
        },
        pageData0: {
          pageNo: 1,
          pageSize: 10
        },
        pageData9: {
          pageNo: 1,
          pageSize: 10
        },
      }, () => {
        this.getData()
      })
    }
  }
  handleFinish = (params) => {
    console.log(params);
  }

  toExportTable = async () => {
    const { salesReturnStatus, searchValue } = this.state
    await apiGetReturnOrderDetails({ ...searchValue, salesReturnStatus, pageNo: 1, pageSize: 5000 }).then(res => {
      if (res.data && res.code === 0) {
        let th_arr = [
          {
            title: '自提退单列表',
            prop: '',
            children: [
              {
                title: "退单编号",
                prop: "returnCode",
              },
              {
                title: "订单编号",
                prop: "orderCode",
              },
              {
                title: "用户昵称",
                prop: "orderMemberName",
              },
              {
                title: "订单金额（元）",
                prop: "orderTotalPrice",
              },
              {
                title: "实付金额（元）",
                prop: "orderPayPrice",
              },
              {
                title: "退款金额",
                prop: "realRefundAmount",
              },
              {
                title: "退单时间",
                prop: "salesGoTime",
              },
              {
                title: "退单状态",
                prop: "salesReturnStatus",
              },
              {
                title: "退单原因",
                prop: "remark",
              },
            ]
          }
        ]
        let tb_arr = []
        res.data.forEach(item => {
          let salesReturnStatus = ''
          switch (item.salesReturnStatus) {
            case 1:
              salesReturnStatus = "退款中"
              break
            case 0:
              salesReturnStatus = "退款失败"
              break
            case 9:
              salesReturnStatus = "退款成功"
              break
            default:
              salesReturnStatus = "未知退款状态"
          }
          tb_arr.push({
            returnCode: item.returnCode || '/',
            orderCode: item.orderCode || '/',
            orderMemberName: item.orderMemberName,
            orderTotalPrice:React.$transNum(item.orderTotalPrice, 2, -2),
            orderPayPrice:React.$transNum(item.orderPayPrice, 2, -2),
            realRefundAmount:React.$transNum(item.realRefundAmount, 2, -2),
            refundWay:item.refundWay || '/',
            salesGoTime:item.salesGoTime,
            salesReturnStatus:salesReturnStatus || '/',
            remark:item.remark || '/'
          })
        });
        exportSheetTable({ fileName: '自提退单列表', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false })
      }
    })
  }
  frozenVisibleCancel = () => {
    this.FormRef.current.resetFields()
    this.setState({
      frozenVisible: false,
    })
  }
  onChange = (value) => {
    this.setState({
      orderPayPrice: value
    });
  };
  render() {
    const operations = {
      right: (
        <Space>
          <Search
            onSearch={(e) => this.setNickName(e)}
            style={{ width: 150 }}
            placeholder={"用户昵称"}
            allowClear
            enterButton
          />
          <Search
            onSearch={(e) => this.setOrderCode(e)}
            style={{ width: 180 }}
            placeholder={"请输入订单号"}
            allowClear
            enterButton
          />
          <Search
            onSearch={(e) => this.setReturnCode(e)}
            style={{ width: 180 }}
            placeholder={"请输入退单号"}
            allowClear
            enterButton
          />
          <div>
            <span>退单时间 </span>
            <RangePicker onChange={(e) => this.datePickerChange(e)} />
          </div>
          <Button onClick={() => this.toExportTable()}>导出</Button>
        </Space>
      ),
    };
    const { tabData, loading, visible, btnLoading, frozenVisible, orderPayPrice } = this.state;
    return (
      <div className="p-layout-box">
        <Tabs
          onChange={(value) => this.setTabKey(value)}
          tabBarExtraContent={operations}
        >
          {tabData.map((v, i) => {
            return (
              <TabPane tab={v.label} key={v.value}>
                <div className="p-layout-content-pagination">
                  <TheTable
                    scroll={{ x: "max-content" }}
                    columns={this.state[`columns${v.value}`]}
                    dataSource={this.state[`dataSource${v.value}`]}
                    loading={loading}
                  />
                  <ThePagination
                    pageNo={this.state[`pageData${v.value}`].pageNo}
                    pageSize={this.state[`pageData${v.value}`].pageSize}
                    total={this.state[`total${v.value}`]}
                    pageChange={(pageNo, pageSize) =>
                      this.pageChange(pageNo, pageSize, v.value)
                    }
                  />
                </div>
              </TabPane>
            );
          })}
        </Tabs>
        <TheDialog
          title="拒绝退款"
          width={600}
          visible={visible}
          footer={null}
          handleCancel={this.handleCancel}
        >
          <Form onFinish={this.onFinish}>
            <Form.Item name={'refuseReason'} label="拒绝原因" rules={[{ required: true }]}>
              <TextArea allowClear maxLength={50} showCount autoSize={{ minRows: 6, maxRows: 6 }} />
            </Form.Item>
            <Form.Item>
              <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                <Space>
                  <Button onClick={this.handleCancel}>取消</Button>
                  <Button loading={btnLoading} type="primary" htmlType="submit">确认</Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </TheDialog>
        <Modal visible={frozenVisible} width="20%"
          onCancel={() => this.frozenVisibleCancel()}
          footer={null}
          title={'您确定要退款吗？'}
        >
          <Form
            labelCol={{
              span: 6,
            }}
            wrapperCol={{
              span: 14,
            }}
            ref={this.FormRef}
            onFinish={(values) => this.modalConfirm(values)}
          >
            <Form.Item
              label={'退款金额'}
              name="changePrice"
              rules={[
                {
                  required: true,
                  message: '请输入退款金额',
                },
              ]}
            >
              <InputNumber placeholder={'请输入退款金额'} defaultValue={orderPayPrice} onChange={this.onChange} />
            </Form.Item>
            <Form.Item wrapperCol={{
              offset: 12,
              span: 16,
            }}>
              <Space size="small" style={{ marginLeft: 10 }}>
                <Button type="default" onClick={() => this.frozenVisibleCancel()}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}

export default Chargeback;
